/**
 * 动态加载外部组件和css
 * @param {string} name 组件名字
 * @param {string} path 组件目录
 * @returns {Promise<*>} 组件实例
 */
export function loadCommAndCss(name, path = '/com/') {
    const src = `${path}${name}/${name}-umd.js`
    return new Promise((resolve, reject) => {
        if (!src || !name) return
        const script = document.createElement('script')
        script.async = true
        script.src = src
        // script.type = 'module'
        document.getElementsByTagName('head')[0].appendChild(script)
        script.onload = () => {
            window[name].name = name
            /*if (window[name][name].__scopeId) {
                // 如果存在css就加载
                const link = document.createElement('link')
                link.type = 'text/css'
                link.rel = 'stylesheet'
                link.href = `${path}${name}/${name}.css`
                document.getElementsByTagName('head')[0].appendChild(link)
            }*/
            resolve(window[name])
        }
        script.onerror = (e) => {
            reject(e)
            console.log(e)
        }
    })
}

// 需要增加px单位的属性
const addPxArr = [
    "width",
    "minWidth",
    "height",
    "minHeight",
    "fontSize",
    "top",
    "right",
    "bottom",
    "left",
];
/**
 * 常用的css样式格式化
 * @param {CSSStyleDeclaration} style 样式
 */
export function styleFormat(style) {
    const attribute = Object.assign({}, style);
    for (const key in attribute) {
        const valStr = attribute[key].toString()
        if (
            addPxArr.includes(key) &&
            !valStr.includes('px') &&
            !valStr.includes('%')
        ) {
            // 需要增加px单位的属性
            attribute[key] = `${attribute[key]}px`;
        } else if (key === "transform") {
            if (/^(-?\d+)(\.\d+)?$/.test(attribute[key])) {
                // 如果是整数或小数 旋转角度增加deg单位
                attribute[key] = `rotate(${attribute[key]}deg)`;
            }
            /* else if(attribute[key].includes('translate')){
              attribute[key] = `translate(${attribute[key]}deg)`
            }*/
        }
    }
    return attribute;
}
